package visiopuce.ui.view;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnViewerToolTipSupport;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.window.ToolTip;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.wb.swt.ResourceManager;

import visiopuce.ApplicationContexte;
import visiopuce.graph.GraphCytog;
import visiopuce.objets.Alteration;
import visiopuce.objets.GeneNcbi;
import visiopuce.service.ReferentielServiceImpl;
import visiopuce.ui.listener.ExportXLSListener;
import visiopuce.ui.providers.GeneTableLabelProvider;

public class GrapheView extends ViewPart {

	public static final String ID = "visiopuce.grapheView";

	private Group grpGraphique;
	private Link linkNCBI;
	private Link linkEnsembl;
	private Link linkDGV;
	private Link linkDecipher;
	private Link linkUCSC;
	private Group grpGnesPrsentsDans;
	private TableViewer tableGenes;
	private int selectedColumn = -1;
	private boolean colonneExiste = false;
	private GraphCytog graph;

	private SelectionAdapter linkSelectionListener;

	private Composite composite;

	public GrapheView() {
		linkSelectionListener = new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				try {
					PlatformUI.getWorkbench().getBrowserSupport().getExternalBrowser().openURL(new URL(e.text));
				} catch (PartInitException ex) {
					// TODO Auto-generated catch block
					ex.printStackTrace();
				} catch (MalformedURLException ex) {
					// TODO Auto-generated catch block
					ex.printStackTrace();
				}
			}
		};
	}

	@Override
	public void createPartControl(Composite parent) {

		final ScrolledComposite sc1 = new ScrolledComposite((Composite) parent, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
		sc1.getVerticalBar().setIncrement(10);
		sc1.getHorizontalBar().setIncrement(10);
		sc1.setAlwaysShowScrollBars(true);

		composite = new Composite(sc1, SWT.NONE);

		sc1.setContent(composite);
		sc1.getVerticalBar().addSelectionListener(new SelectionListener() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				if (graph != null) {
					graph.repaint();
				}
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				// TODO Auto-generated method stub

			}

		});

		composite.setLayout(new GridLayout(1, true));
		grpGraphique = new Group(composite, SWT.NONE);
		grpGraphique.setText("Graphique");
		grpGraphique.setLayout(new GridLayout(1, false));
		GridData gd_grpGraphique = new GridData(SWT.FILL, SWT.CENTER, true, true, 4, 4);
		grpGraphique.setLayoutData(gd_grpGraphique);

		Group grpLiensVersDautres = new Group(composite, SWT.NONE);
		grpLiensVersDautres.setLayout(new GridLayout(6, false));
		grpLiensVersDautres.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 4, 1));
		grpLiensVersDautres.setText("Liens vers d'autres bases :");

		linkNCBI = new Link(grpLiensVersDautres, SWT.NONE);
		linkNCBI.setText("<a>NCBI Map Viewer</a>");
		linkNCBI.addSelectionListener(linkSelectionListener);

		linkEnsembl = new Link(grpLiensVersDautres, SWT.NONE);
		linkEnsembl.setText("<a>ENSEMBL</a>");
		linkEnsembl.addSelectionListener(linkSelectionListener);

		linkDGV = new Link(grpLiensVersDautres, SWT.NONE);
		linkDGV.setText("<a>DGV</a>");
		linkDGV.addSelectionListener(linkSelectionListener);

		linkDecipher = new Link(grpLiensVersDautres, SWT.NONE);
		linkDecipher.setText("<a>Decipher</a>");
		linkDecipher.addSelectionListener(linkSelectionListener);

		linkUCSC = new Link(grpLiensVersDautres, SWT.NONE);
		linkUCSC.setText("<a>UCSC</a>");
		linkUCSC.addSelectionListener(linkSelectionListener);

		// linkPubMedBande = new Link(grpLiensVersDautres, SWT.NONE);
		// linkPubMedBande.setText("<a>PubMed par bande chromosomique</a>");

		grpGnesPrsentsDans = new Group(composite, SWT.NONE);
		GridData gd_grpGnesPrsentsDans = new GridData(SWT.LEFT, SWT.FILL, true, false, 4, 1);
		// gd_grpGnesPrsentsDans.widthHint = 559;
		grpGnesPrsentsDans.setLayoutData(gd_grpGnesPrsentsDans);
		grpGnesPrsentsDans.setLayout(new GridLayout(1, false));
		grpGnesPrsentsDans.setText("G\u00E8nes chevauchants le CNV");

		tableGenes = new TableViewer(grpGnesPrsentsDans, SWT.BORDER | SWT.FULL_SELECTION);
		tableGenes.getTable().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		tableGenes.getTable().setHeaderVisible(true);
		tableGenes.getTable().setLinesVisible(true);
		tableGenes.setContentProvider(ArrayContentProvider.getInstance());
		tableGenes.getTable().addListener(SWT.MouseDown, new Listener() {
			public void handleEvent(Event event) {
				Point pt = new Point(event.x, event.y);
				TableItem item = tableGenes.getTable().getItem(pt);
				if (item != null) {
					for (int col = 0; col < tableGenes.getTable().getColumnCount(); col++) {
						Rectangle rect = item.getBounds(col);
						if (rect.contains(pt)) {
							selectedColumn = col;
						}
					}
				}
			}
		});

		tableGenes.addDoubleClickListener(new IDoubleClickListener() {

			@Override
			public void doubleClick(DoubleClickEvent event) {
				Object selectedItem = ((StructuredSelection) event.getSelection()).getFirstElement();
				String url = "";
				if (selectedItem instanceof GeneNcbi) {

					GeneNcbi gene = (GeneNcbi) selectedItem;
					switch (selectedColumn) {
					case 0:
						url = "http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=gene&amp;cmd=retrieve&amp;dopt=full_report&amp;list_uids=" + gene.getId().getIdNcbi();
						break;
					case 1:
						url = null;
						break;
					case 2: {
						url = null;
						break;
					}
					case 3:
						url = null;
						break;
					case 4: {
						if (gene.getDisorderMimnb() != null) {
							String[] numeros = gene.getDisorderMimnb().split("\\|");
							url = "";
							for (String numero : numeros) {
								url += "http://omim.org/entry/" + numero + "|";
							}

						} else {
							url = "-";
						}
						break;
					}

					case 5: {
						url = null;
						break;
					}
					case 6: {
						url = null;
						break;
					}
					case 7: {
						if (gene.getMimnb() != null) {
							url = "http://omim.org/entry/" + gene.getMimnb();
						} else {
							url = null;
						}
						break;
					}
					case 8:
						url = "http://www.genecards.org/cgi-bin/carddisp.pl?gene=" + gene.getSymbol();
						break;

					case 9:
						url = "http://www.ensembl.org/Human/Search/Results?q=" + gene.getSymbol() + ";y=0;site=ensembl;x=0;facet_species=Human;page=1;facet_feature_type=Gene";
						break;
					case 10:
						url = "http://www.ncbi.nlm.nih.gov/pubmed?term=" + gene.getSymbol();
						break;

					case 11:
						url = "http://www.ncbi.nlm.nih.gov/gquery/?term=" + gene.getSymbol();
						break;

					case 12:
						url = "http://projects.tcag.ca/variation/search.asp?source=hg19&table=Locus&filtre=&show=table&exactMatch=no&keyword=" + gene.getSymbol();
						break;

					case 13:
						url = "http://genome.ucsc.edu/cgi-bin/hgGene?hgg_type=knownGene&db=hg19&hgg_gene=" + gene.getSymbol();
						break;
					}
					try {
						if (url != null && !url.isEmpty() && url.contains("http:")) {
							String[] urls = url.split("\\|");
							for (String uri : urls) {
								PlatformUI.getWorkbench().getBrowserSupport().getExternalBrowser().openURL(new URL(uri));
							}
						}
					} catch (PartInitException | MalformedURLException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
				// process selectedItem which is our row item as provided
				// by our IStructuredContentProvider, selectedColumn
				// is the index of column (or -1 if there was problem)
			}
		});

		Alteration alt = ApplicationContexte.getInstance().getRegionRechercheEnCours();

		Button export = new Button(grpGnesPrsentsDans, SWT.BORDER | SWT.FULL_SELECTION);
		export.setImage(ResourceManager.getPluginImage("visiopuce", "icons/Excel-icon.png"));
		export.addSelectionListener(new ExportXLSListener(tableGenes, "chr" + alt.getChromosome() + "_" + alt.getDebutHg19() + "-" + alt.getFinHg19()));

		List<GeneNcbi> genes = ReferentielServiceImpl.getInstance().getGeneNCBIByBorne(alt, 0);
		createColumns();
		tableGenes.setInput(genes);

		grpGnesPrsentsDans.pack();

		linkNCBI.setText("<a href=\"http://www.ncbi.nlm.nih.gov/projects/mapview/maps.cgi?TAXID=9606&CHR=" + alt.getChromosome() + "&MAPS=ideogr%2Ccntg-r%2Cregions%2CugHs%2Cgenes&BEG=" + alt.getDebutHg19() + "&END=" + alt.getFinHg19() + "&oview=default\">NCBI Map Viewer</a>");
		linkEnsembl.setText("<a  href=\"http://www.ensembl.org/Homo_sapiens/Location/View?r=" + alt.getChromosome() + "%3A" + alt.getDebutHg19() + "-" + alt.getFinHg19() + "\">ENSEMBL</a>");
		linkDGV.setText("<a  href=\"http://dgv.tcag.ca/gb2/gbrowse/dgv2_hg19/?name=chr" + alt.getChromosome() + "%3A" + alt.getDebutHg19() + "-" + alt.getFinHg19() + ";search=Search\">DGV</a>");
		linkDecipher.setText("<a  href=\"https://decipher.sanger.ac.uk/search?q=" + alt.getChromosome() + "%3A" + alt.getDebutHg19() + "-" + alt.getFinHg19() + "\">Decipher</a>");
		linkUCSC.setText("<a  href=\"http://genome.ucsc.edu/cgi-bin/hgTracks?position=chr" + alt.getChromosome() + ":" + alt.getDebutHg19() + "-" + alt.getFinHg19() + "\">UCSC</a>");

		if (graph == null) {
			graph = new GraphCytog(grpGraphique, alt, true);

		}
		grpGraphique.pack();
		composite.pack();
	}

	private void createColumns() {
		if (!colonneExiste) {
			String[] titles = new String[] { "Nom", "Direction", "Type", "Description", "Omim Morbid", "Cancer", "RM/TED", "Omim", "Genecards", "ENSEMBL", "Pubmed", "NCBI Entrez", "DGV", "UCSC" };
			int[] bounds = { 70, 20, 50, 200, 70, 30, 30, 50, 50, 50, 50, 50, 50, 50 };

			TableViewerColumn columnNom = createTableViewerColumn(titles[0], bounds[0], 0);
			TableViewerColumn column2 = createTableViewerColumn(titles[1], bounds[1], 1);
			TableViewerColumn column3 = createTableViewerColumn(titles[2], bounds[2], 2);
			TableViewerColumn column4 = createTableViewerColumn(titles[3], bounds[3], 3);
			TableViewerColumn column5 = createTableViewerColumn(titles[4], bounds[4], 4);
			TableViewerColumn column6 = createTableViewerColumn(titles[5], bounds[5], 5);
			TableViewerColumn column7 = createTableViewerColumn(titles[6], bounds[6], 6);
			TableViewerColumn column8 = createTableViewerColumn(titles[7], bounds[7], 7);
			TableViewerColumn column9 = createTableViewerColumn(titles[8], bounds[8], 8);
			TableViewerColumn column10 = createTableViewerColumn(titles[9], bounds[9], 9);
			TableViewerColumn column11 = createTableViewerColumn(titles[10], bounds[10], 10);
			TableViewerColumn column12 = createTableViewerColumn(titles[11], bounds[11], 11);
			TableViewerColumn column13 = createTableViewerColumn(titles[12], bounds[12], 12);
			TableViewerColumn column14 = createTableViewerColumn(titles[13], bounds[13], 13);
			colonneExiste = true;
		}
	}

	private TableViewerColumn createTableViewerColumn(String header, int width, int idx) {
		TableViewerColumn column = new TableViewerColumn(tableGenes, SWT.LEFT, idx);
		column.getColumn().setText(header);
		column.getColumn().setWidth(width);
		column.getColumn().setResizable(true);
		column.getColumn().setMoveable(true);
		column.setLabelProvider(new GeneTableLabelProvider(idx));
		ColumnViewerToolTipSupport.enableFor(column.getViewer(), ToolTip.NO_RECREATE);
		return column;
	}

	@Override
	public void setFocus() {
		// TODO Auto-generated method stub

	}

}
